package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorsMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorsMapper dishFlavorsMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @Transactional
    public void saveDishWithFlavors(DishDTO dishDto) {
        Dish dish = new Dish();
        //将dishDto对应数值复制到dish中
        BeanUtils.copyProperties(dishDto, dish);
        //向菜品表中插入一条数据, 同时把数据库表的主键id回显给dish的属性id
        dishMapper.insert(dish);

        //获取insert语句生成的主键值
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDto.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            //绑定菜品id
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
            //向插入菜品的口味表中插入n条数据
            dishFlavorsMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品分页查询
     *
     * @return
     */
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

        long total = page.getTotal();
        List<DishVO> result = page.getResult();

        return new PageResult(total, result);
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     * @return
     */
    @Transactional
    public void deleteDish(List<Long> ids) {
        for (Long id : ids) {
            //判断当前菜品是否能删除---是否存在起售中的菜品?
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus().equals(StatusConstant.ENABLE)) {
                //菜品起售中, 不能删除, 抛出异常
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }

            //删除菜品关联的口味数据
            List<DishFlavor> getByDishId = dishFlavorsMapper.getByDishId(id);
            if (getByDishId != null && getByDishId.size() > 0) { //先判断该菜品是否有口味
                //再把菜品相关的口味全部删除
                dishFlavorsMapper.deleteByDishIds(ids);
            }
        }

        //判断当前菜品是否能删除---是否被套餐关联了
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            //菜品被套餐关联了, 不能删除, 抛出异常
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }


        //删除菜品表中的菜品数据
        dishMapper.deleteDish(ids);

    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    public List<Dish> getByCategoryId(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .build();
        return dishMapper.select(dish);
    }

    /**
     * 根据id查询菜品及其口味
     *
     * @param id
     * @return
     */
    public DishVO getByIdWithFlavors(Long id) {
        //根据id查询菜品
        Dish dish = dishMapper.getById(id);

        //根据菜品id查询其口味
        List<DishFlavor> dishFlavors = dishFlavorsMapper.getByDishId(id);

        //封装属性到DishVO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     * @return
     */
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        //拷贝需要修改的属性给Dish封装
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        Long dishId = dish.getId(); //获取菜品的id

        //先修改菜品基本属性
        dishMapper.update(dish);

        //再对菜品对应的口味表进行修改
        List<DishFlavor> getByDishId = dishFlavorsMapper.getByDishId(dishId);
        if (getByDishId != null && getByDishId.size() > 0) { //判断该菜品是否有口味
            //1.先直接把菜品相关的口味全部删除
            dishFlavorsMapper.deleteByDishId(dishId);
        }
        //2.再把菜品相关口味重新插入
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        //判断传过来的口味是否为空
        if (dishFlavors != null && dishFlavors.size() > 0) {
            //给口味绑定菜品id
            dishFlavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
            //批量插入
            dishFlavorsMapper.insertBatch(dishFlavors);
        }
    }

    /**
     * 启售停售菜品
     *
     * @param status
     * @param id
     * @return
     */
    @Transactional
    public void startOrStop(Long id, Integer status) {
        //启售停售菜品
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        //如果是停售, 同时需将包含该菜品的套餐也停售
        if (status.equals(StatusConstant.DISABLE)) {
            //获取套餐id
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(Collections.singletonList(id));
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setMealId : setmealIds) {
                    //修改套餐的状态为禁售
                    Setmeal setmeal = Setmeal.builder()
                            .id(setMealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * 根据分类id查询菜品及其口味
     *
     * @param id
     * @return
     */
    public List<DishVO> getByCategoryIdWithFlavors(Long id) {
        //根据id查询菜品
        List<Dish> dishList = dishMapper.getByCategoryId(id);
        //创建List, 用与存储返回数据
        List<DishVO> dishVOList = new ArrayList<>();

        dishList.forEach(dish -> {
            //创建dishVO, 用于存储中间数据
            DishVO dishVO = new DishVO();
            //如果菜品是起售中才进行查询
            if (dish.getStatus().equals(StatusConstant.ENABLE)) {
                //根据菜品id查询其口味
                List<DishFlavor> dishFlavors = dishFlavorsMapper.getByDishId(dish.getId());
                //数据拷贝
                BeanUtils.copyProperties(dish, dishVO);
                //给flavors赋值
                dishVO.setFlavors(dishFlavors);
                //添加数据
                dishVOList.add(dishVO);
            }
        });

        return dishVOList;
    }


}
